/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { withRouter } from 'umi';
import { Spin, Empty, message } from 'antd';
import { Link }  from 'umi';
import { useRequest, defaultFormatResult, useWorkFlow } from '@/hooks';
import {
    CollapseHeader,
    ProfileCard,
    WorkHandoverTable,
    VacationTable,
    AccountTable,
    AdministrativeTable,
    PayrollComputationTable
} from './components';
import styles from './index.less';
import {
    getHandoverDetailByOrderId,
    getSystemTodoList,
    getLeavePayroll,
    queryVocationList,
    getColumnlist
} from '../service';

function HandoverDetail({ location }) {
    const { query } = location;
    const { employeeCode, dimissionOrderId } = query;
    const [hasRequestFlag, setHasRequestFlag] = React.useState(false); // 判断是否已经调过获取假期的接口，避免重复调用
    const [vacationOptions, setVacationOptions] = React.useState({});
    const [vocationList, setVocationList] = React.useState([]);
    const [vacationLoading2, setVacationLoading2] = React.useState(true);
    const { data, loading } = useRequest(() => getHandoverDetailByOrderId(dimissionOrderId), {
        ready: !!dimissionOrderId,
        ...defaultFormatResult
    });
    // const params = {
    //     pageNo: 1,
    //     pageSize: 10000,
    //     taskStatus: '0'
    // };
    // // 获取工作安排--系统待办事项
    // // employeeCode: oa1145573189141659650
    // const { data: systemTododata, loading: systemTodoloading } = useRequest(
    //     () => getSystemTodoList(params, employeeCode),
    //     { ...defaultFormatResult }
    // );
    // 获取薪资总额
    const params2 = {
        employeeCode,
        organizationCode: data?.dimissionOrderVO.companyCode
    };
    const { data: leavePayrollData, run: getLeavePayrollData, loading: leavePayrollLoading } = useRequest(
        () => getLeavePayroll(params2),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    React.useMemo(() => {
        if (data) getLeavePayrollData();
    }, [data]);
    // 获取假期数据
    const params3 = {
        // companyCode: 'ORG15540490989436999',
        companyCode: data?.dimissionOrderVO.companyCode,
        // employeeCodes: ['oa1420013715800248321'],
        employeeCodes: [employeeCode],
        pageNo: 1,
        pageSize: 50
    };
    const { run: getVocationList, loading: vacationLoading } = useRequest(() => queryVocationList(params3), {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data: data3, msg } = res;
                if (code === 10000) {
                    if (data3.rows[0]?.vocationList.length > 0) {
                        const list = data3.rows[0]?.vocationList
                            .filter(item => vacationOptions[item.leaveCode].openState === '1')
                            .map(item => {
                                // remainDuration:剩余时长， discountingDurationUpperLimit：折现天数
                                // 接口给的都是分钟，展示要分小时、天，传给后台分钟
                                // 一天8小时制
                                const temp = {
                                    holidayName: vacationOptions[item.leaveCode].leaveName,
                                    // remainDuration:
                                    //     item.leaveCode === 'CommonYear'
                                    //         ? (item.value / (8 * 60)).toFixed(2)
                                    //         : Number(item.value),
                                    remainDuration: Number(item.value),
                                    durationType: 1,
                                    holidayCode: item.leaveCode
                                };
                                return temp;
                            });
                        setVocationList([...list]);
                    }
                    setVacationLoading2(false);
                    return data3;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    // 获取假期类型选项
    // useRequest(() => getColumnlist('ORG15540490989436999'), {
    const { run: getVacationType } = useRequest(() => getColumnlist(data?.dimissionOrderVO.companyCode), {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data: data2, msg } = res;
                if (code === 10000) {
                    const options = {};
                    for (let i = 0, len = data2.length; i < len; i += 1) {
                        // options[data2[i].leaveCode] = data2[i].leaveName;
                        options[data2[i].leaveCode] = { leaveName: data2[i].leaveName, openState: data2[i].openState };
                    }
                    setVacationOptions(options);
                    getVocationList();
                    setVacationLoading2(false);
                    return options;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    const workContent = item => (
        <div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
            {/* <div className={styles.itemBox}>离职人员的系统待办事项：</div>
            <WorkHandoverTable systemTododata={systemTododata} loading={systemTodoloading} type="showShort" /> */}
            <div className={styles.itemBox}>离职前的绩效评定：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
        </div>
    );
    const personnelContent = item => {
        if (item.matterStatus !== 3 && !hasRequestFlag) {
            setHasRequestFlag(true);
            getVacationType();
        }
        return (
            <div>
                <div className={styles.itemBox}>假期结算</div>
                <VacationTable
                    type="detail"
                    value={item.matterStatus === 3 ? item.handoverHolidays : vocationList}
                    vacationLoading={item.matterStatus !== 3 && (vacationLoading || vacationLoading2)}
                />
                {data.handoverSettings.hrHandoverTypes.includes(3) && (
                    <div className={styles.itemBox}>
                        公积金/社保停缴{data.handoverSettings.stopPaymentPfsiType === 1 ? '月份' : '日期'}：
                        <span className={styles.val}>{item.stopPaymentPfsi}</span>
                    </div>
                )}
            </div>
        );
    };
    const ITContent = item => (
        <div>
            <div className={styles.itemBox}>需回收以下资产：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
            <div className={styles.itemBox}>需关闭以下账号：</div>
            <AccountTable value={item.handoverAccount} type="detail" />
        </div>
    );
    // 行政交接
    const administrationContent = item => (
        <div>
            <div className={styles.itemBox}>需回收以下资产：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
            <div className={styles.itemBox}>按说明完成以下事项：</div>
            <AdministrativeTable value={item.otherBusines} type="detail" />
        </div>
    );
    // 财务清算
    const financeContent = item =>
        data?.handoverSettings.containSalaryFlag === 1 || data?.dimissionOrderVO.dimissionType === 2 ? (
            <div>
                <div className={styles.itemBox}>
                    结算时间：
                    <span className={styles.val}>
                        {item.settlementTimeType === 1 ? '随下一个发薪日统一结算' : '立即结算'}
                    </span>
                </div>
                <div className={styles.itemBox}>薪资明细：</div>
                <PayrollComputationTable
                    type="detail"
                    leavePayrollData={leavePayrollData}
                    loading={leavePayrollLoading}
                    compensation={data?.dimissionOrderVO.compensation}
                    dimissionType={data?.dimissionOrderVO.dimissionType}
                    containSalaryFlag={data?.handoverSettings.containSalaryFlag}
                />
                <div className={styles.itemBox}>
                    总计：<span className={styles.val}>{item.total}</span>
                </div>
            </div>
        ) : null;
    const matchObj = {
        1: {
            title: '工作安排：',
            department: '用人',
            content: workContent
        },
        2: {
            title: '人事交接：',
            department: '人事',
            content: personnelContent
        },
        3: {
            title: 'IT 交接：',
            department: 'IT',
            content: ITContent
        },
        4: {
            title: '行政交接：',
            department: '行政',
            content: administrationContent
        },
        5: {
            title: '财务清算：',
            department: '财务',
            content: financeContent
        }
    };
    const Box = (item, index) => (
        <CollapseHeader key={index} title={matchObj[item.handoverType].title} matterStatus={item.matterStatus}>
            <div className={styles.itemBox}>
                处理人：<span className={styles.val}>{item.dealEmployeeName}</span>
            </div>
            {matchObj[item.handoverType].content(item)}
            <div className={styles.itemBox}>
                {matchObj[item.handoverType].department}部门备注：{' '}
                {item.remark ? <span className={styles.val}>{item.remark}</span> : '--'}
            </div>
        </CollapseHeader>
    );
    const { view } = useWorkFlow({ launchParam: { type: 'TransferPositionApply' } });
    // 跳转到审批、审批详情页面
    const gotoApprovePage = () => {
        view({ processInstanceId: data?.dimissionOrderVO.processInstanceId });
    };
    return (
        <div className={styles.handover_container}>
            <div className={styles.top_card}>
                <ProfileCard employeeCode={employeeCode} />
            </div>
            <Spin spinning={loading}>
                <div className={styles.line}></div>
                <div className={styles.content}>
                    <div>
                        <span>离职申请：</span>
                        <span style={{ color: '#ffb957', cursor: 'pointer' }} onClick={gotoApprovePage}>
                            查看详情
                        </span>
                        {/* <Link>
                            查看详情
                        </Link> */}
                    </div>
                    <div>
                        <span>离职日期：</span>
                        <span>{data?.dimissionOrderVO.finalDimissionDate || '--'}</span>
                    </div>
                </div>
                {data && data.matterDetail.map(item => Box(item))}
            </Spin>
        </div>
    );
}

export default withRouter(HandoverDetail);
